package com.biz.controller.api;

import com.alibaba.fastjson.JSON;
import com.biz.model.Pmodel.basic.Base90Detail;
import com.biz.service.api.ApiInterfaceServiceI;
import com.framework.controller.BaseController;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

import static org.apache.commons.lang3.Validate.notNull;

/**
 * 用户的余额接口，包括久零券和久零贝
 * Created by 曹凯 on 2017/2/24.
 */
@Controller
@RequestMapping("/api/balance")
public class BalanceController extends BaseController {
    @Resource(name = "apiInterfaceService")
    private ApiInterfaceServiceI apiInterfaceService;
/**
     * 用户积分接口
     */
    @RequestMapping(value="/operUserBalance")
    public synchronized void operUserBalance(@RequestParam(value="json", required=true) String json, HttpServletResponse response){
        Map<String,Object> map=new HashMap<String, Object>();
        Map<String,Object> res = new HashMap<String, Object>();
        try {
            map= JSON.parseObject(json,Map.class);
            res=apiInterfaceService.updateUserBalance(map);//处理用户积分
        } catch (Exception e) {
            res.put("flag", "1");
            res.put("msg","操作失败,参数错误");
        }
        writeJson(res,response);
    }


    /**
     * 积分明细--领取
     * @throws Exception
     */
    @RequestMapping(value = "/orther_balance_in")
    public void orther_balance_in(String open_id,String page,HttpServletResponse response)
    {
        JSONObject jSONObject = new JSONObject();
        Map<String,Object> pd = new HashMap<>();
        logger.error("积分明细--领取接口=open_id=" + open_id);
        if(StringUtils.isBlank(open_id)){
            jSONObject.put("return_code", 0);
            jSONObject.put("return_info", "接口参数错误：open_id为空");
            jSONObject.put("return_data", null);

        }
        else
        { pd.put("open_id", open_id);
            pd.put("state", "in");
            int page_int = Integer.valueOf(page);
            int pageSize = 10;
            pd.put("pageSize", pageSize);
            pd.put("pageNum", pageSize * (page_int - 1));

            try {

                //领取金额
                List<Base90Detail> intList = apiInterfaceService.selectOrtherBalanceIn(pd);
                Collections.sort(intList,new ComparatorBase90Deatil());
                for (Base90Detail item : intList) {
                    String create_time = item.getCreate_time();
                    String c_time = create_time.substring(0, create_time.lastIndexOf(" "));
                    item.setCreate_time(c_time);
                }
                //领取总额
                int int_sum = apiInterfaceService.int_sum(pd);
                JSONObject jsonObject_sum = new JSONObject();
                jsonObject_sum.put("int_sum", int_sum);
                JSONArray jsonStrs = new JSONArray();
                for (Base90Detail Detail : intList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("create_time", notNull(Detail.getCreate_time()));
                    jsonObject.put("source", Detail.getSource());
                    jsonObject.put("business_name", Detail.getBusiness_name());
                    jsonObject.put("source_msg", notNull(Detail.getSource_msg()));
                    jsonObject.put("point_90", Detail.getPoint_90());
                    jsonStrs.add(jsonObject);
                }
                jsonStrs.add(jsonObject_sum);
                jSONObject.put("return_code", 1);
                jSONObject.put("return_info", "");
                jSONObject.put("return_data", jsonStrs);
            } catch (Exception e) {
                jSONObject.put("return_code", 0);
                jSONObject.put("return_info", e.getMessage());
                jSONObject.put("return_data", null);
                logger.error("积分明细--领取=报错=" ,e.fillInStackTrace());
                e.printStackTrace();
            }
        }
        writeJson(jSONObject,response);
    }

    class ComparatorBase90Deatil implements Comparator<Base90Detail> {

        @Override
        public int compare(Base90Detail o1, Base90Detail o2) {
            SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
            Date dateO1= null;
            Date dateO2=null;
            try {
                dateO1 = sdf.parse(o1.getCreate_time());
                dateO2 = sdf.parse(o2.getCreate_time());

                if(dateO1.after(dateO2)){
                    return -1;
                }
            } catch (ParseException e) {
                e.printStackTrace();
                logger.error(e.fillInStackTrace());
                return 0;
            }
            return 1;
        }
    }


    /**
     * 积分明细--消费
     */
    @RequestMapping(value = "/orther_balance_out")
    public void orther_balance_out(String open_id,String page,HttpServletResponse response)
    {
        JSONObject jSONObject = new JSONObject();
        Map<String,Object> pd = new HashMap<>();
        logger.error("积分明细--消费接口=open_id=" + open_id);
        if(StringUtils.isBlank(open_id)){
            jSONObject.put("return_code", 0);
            jSONObject.put("return_info", "接口参数错误：open_id为空");
            jSONObject.put("return_data", null);
        }
        else {
            pd.put("open_id", open_id);
            int page_int = Integer.valueOf(page);
            int pageSize = 10;
            pd.put("pageSize", pageSize);
            pd.put("pageNum", pageSize * (page_int - 1));

            try {
                //消费金额
                //联盟商户退款金额
                pd.put("state","RefLM");
                pd.put("source", 3);
                List<Base90Detail> outList = apiInterfaceService.selectOrtherBalanceOut(pd);

                Collections.sort(outList,new ComparatorBase90Deatil());
                for (Base90Detail item : outList) {
                    String create_time = item.getCreate_time();
                    String c_time = create_time.substring(0, create_time.lastIndexOf(" "));
                    item.setCreate_time(c_time);
                }

                //消费总额
                int out_sum = apiInterfaceService.out_sum(pd);
                JSONObject jsonObject_sum = new JSONObject();
                jsonObject_sum.put("out_sum", out_sum);
                JSONArray jsonStrs = new JSONArray();
                for (Base90Detail Detail : outList) {
                    JSONObject jsonObject = new JSONObject();
                    jsonObject.put("create_time", notNull(Detail.getCreate_time()));
                    jsonObject.put("source", Detail.getSource());
                    jsonObject.put("business_name", Detail.getBusiness_name());
                    jsonObject.put("source_msg", notNull(Detail.getSource_msg()));
                    jsonObject.put("point_90", Detail.getPoint_90());
                    jsonStrs.add(jsonObject);
                }
                jsonStrs.add(jsonObject_sum);
                jSONObject.put("return_code", 1);
                jSONObject.put("return_info", "");
                jSONObject.put("return_data", jsonStrs);
            } catch (Exception e) {
                jSONObject.put("return_code", 0);
                jSONObject.put("return_info", e.getMessage());
                jSONObject.put("return_data", null);
                logger.error("积分明细--消费=报错=" ,e.fillInStackTrace());
                e.printStackTrace();
            }
        }

        writeJson(jSONObject,response);
    }


}
